/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ni;

/**
 *
 * @author Arnaud
 */
// TCPClient.java
// A client program implementing TCP socket
import controller.ChatController;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import protocol.Port;

public class TCPClient extends Thread {

    int serverPort;
    Socket socket = null;
    File fileToSend;
    ChatController controller;

    public TCPClient(InetAddress serverAddress, File fileToSend, ChatController c) {// arguments supply message and hostname of destination

        try {
            serverPort = Port.receptionTCP;
            this.fileToSend = fileToSend;
            controller = c;

            socket = new Socket(serverAddress, serverPort);

            this.start();

        } catch (IOException ex) {
            System.out.println("Socket client: " + ex.getMessage());
        }
    }

    public void run() {
        
        try {

            FileInputStream fis = new FileInputStream(fileToSend);
            BufferedInputStream bis = new BufferedInputStream(fis);
            
            OutputStream os = socket.getOutputStream();
            
            int count;
            byte[] buffer = new byte[8192];
            while ((count = bis.read(buffer, 0, buffer.length)) > 0)
            {
                os.write(buffer, 0, count);
                os.flush();
            }
            
            controller.controllerDisplayFileArrived(fileToSend.getName());
        } 
        catch (UnknownHostException e) 
        {
            System.out.println("Sock:" + e.getMessage());
        } 
        catch (EOFException e) 
        {
            System.out.println("EOF:" + e.getMessage());
        } 
        catch (IOException e) 
        {
            System.out.println("IO:" + e.getMessage());
        } 
        finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {/*close failed*/

                }
            }
        }
    }
}
